package com.bwie.auth.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.bwie.auth.remote.SysUserRemoteService;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.Constants;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.doamin.dto.LoginDTO;
import com.bwie.common.doamin.dto.RegisterDTO;
import com.bwie.common.doamin.model.SysUser;
import com.bwie.common.doamin.vo.LoginVO;
import com.bwie.common.exceptions.BizException;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:2943147140@qq.com">刘洋朔</a>
 * @version 1.0
 * @description:
 * @date 2025/9/9 10:40
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private SysUserRemoteService sysUserRemoteService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 用户登录
     * @param loginDTO
     * @return
     */
    @Override
    public LoginVO login(@Valid LoginDTO loginDTO) {
        Result<SysUser> sysUserResult = sysUserRemoteService.selLoginInfo(loginDTO);
        //业务错误
        if(sysUserResult.getCode() == Constants.ERROR){
            throw new BizException(sysUserResult.getMsg());
        }
        //查询结果为空
        SysUser sysUserResultData = sysUserResult.getData();
        if(ObjectUtils.isEmpty(sysUserResult)){
            throw new BizException("用户不存在,请先注册");
        }
        //存在为登录成功,存储redis
        HashMap<String, Object> claims = new HashMap<>();
        String userKey = IdUtil.fastSimpleUUID();
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey,sysUserResultData,30, TimeUnit.MINUTES);
        //生成令牌
        claims.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(claims);
        //返回结果
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        loginVO.setLessTime("30MIN");
        loginVO.setUsername(sysUserResultData.getUsername());
        //获取对应角色’
        Long userId = sysUserResultData.getId();
        Result<Long> longResult = sysUserRemoteService.selRoleByUserId(userId);
        //业务错误
        if(sysUserResult.getCode() == Constants.ERROR){
            throw new BizException(sysUserResult.getMsg());
        }
        //查询结果为空
        Long roleId = longResult.getData();
        if(ObjectUtils.isEmpty(roleId)){
            throw new BizException("用户还未绑定角色哦,请联系管理员");
        }
        loginVO.setRoleId(roleId);
        return loginVO;
    }

    /**
     * 获取手机号发送验证码
     * @param phone
     */
    @Override
    public void sendCode(String phone) {
        //手机号校验
        if(!phone.matches("^1[3-9][0-9]{9}$")){
            throw new BizException("手机格式不合法");
        }
        //进行发送验证码
        kafkaTemplate.send("sendCode",phone);
    }

    /**
     * 用户注册
     * @param registerDTO
     */
    @Override
    public void register(RegisterDTO registerDTO) {
        Result<Void> register = sysUserRemoteService.register(registerDTO);
        //业务错误
        if(register.getCode() == Constants.ERROR){
            throw new BizException(register.getMsg());
        }
    }
}
